﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using SmartLib.Cfg;
using System.Linq.Expressions;
using System.Reflection;
using SmartLib.Reflection.Dynamic;

namespace SmartLib.Dal
{
    /// <summary>
    /// DB工厂
    /// </summary>
    public class DBFactory
    {
        private DBFactoryElement _element;

        private DynamicConstructor.InvokeConstructor _createConnectionExecute;
        private DynamicConstructor.InvokeConstructor _createCommandExecute;

        internal DBFactory(DBFactoryElement element)
        {
            _element = element;

            Type connectionType = Type.GetType(element.ConnectionType);
            Type commandType = Type.GetType(element.CommandType);

            _createConnectionExecute = DynamicConstructor.CompileConstructor(connectionType);

            _createCommandExecute = DynamicConstructor.CompileConstructor(commandType);
        }

        /// <summary>
        /// 获取DbConnection
        /// </summary>
        /// <returns>DbConnection</returns>
        public DbConnection CreateDbConnection()
        {
            DbConnection conn = (DbConnection)_createConnectionExecute();
            conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[_element.Name].ConnectionString;
            
            return conn;
        }

        /// <summary>
        /// 获取DbCommand
        /// </summary>
        /// <returns>DbCommand</returns>
        public DbCommand CreateDbCommand()
        {
            return (DbCommand)_createCommandExecute();
        }

        /// <summary>
        /// 获取DbParameter
        /// </summary>
        /// <param name="cmd">DbCommand</param>
        /// <returns>DbParameter</returns>
        public DbParameter CreateParameter(DbCommand cmd)
        {
            return cmd.CreateParameter();
        }

        /// <summary>
        /// 获取带参前缀
        /// </summary>
        public string ParameterToken
        {
            get
            {
                return _element.ParameterToken;
            }
        }
    }
}
